package com.rj.core.algorithm;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * HMAC算法枚举
 */
public enum HmacAlgorithm {
    /**
     * SHA512
     */
    HMAC_SHA512("HmacSHA512"),
    /**
     * SHA256
     */
    HMAC_SHA256("HmacSHA256"),
    /**
     * SHA1
     */
    HMAC_SHA1("HmacSHA1");

    public final String algorithmName;

    HmacAlgorithm(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    /**
     * 计算HMAC
     */
    public byte[] computeHmac(byte[] data, byte[] key) {
        try {
            Mac mac = Mac.getInstance(algorithmName);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithmName);
            mac.init(secretKeySpec);
            return mac.doFinal(data);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("HMAC计算失败: " + e.getMessage(), e);
        }
    }
}